package com.atguigu.tingshu.album.util;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/***
 * 文件上传工具类
 */
@Component
public class FileUtil {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    MinioClient minioClient;

    /**
     * 图片上传接口方法
     * @param file
     * @return
     */
    @SneakyThrows
    public String fileUpload(@RequestParam MultipartFile file){
        if(!minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(minioConstantProperties.getBucketName()).build())){
            // 若不存在，创建桶
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioConstantProperties.getBucketName()).build());
        }
        // 确认桶存在后保存文件
        String fileName = UUID.randomUUID().toString().replace("-", "");
        minioClient.putObject(PutObjectArgs.builder()
                .object(fileName).stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .bucket(minioConstantProperties.getBucketName()).build());
        // 返回文件url给前台
        return minioConstantProperties.getEndpointUrl()+"/"
                +minioConstantProperties.getBucketName()+"/"
                +fileName;

    }

    /**
     * 根据文件名删除文件
     * @param fileName
     */
    @SneakyThrows
    public void deleteFile(String fileName){
        String[] split = fileName.split("/");
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .object(split[split.length-1]).build());
    }

    /**
     * 下载文件至本地
     * @param fileName
     * @param localPath
     */
    @SneakyThrows
    public void fileDownload(String fileName,String localPath){
        // 获取对象参数
        GetObjectArgs objectArgs = GetObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .object(fileName).build();
        // 从对象参数获取流
        InputStream objStream = minioClient.getObject(objectArgs);
        // 将流复制到文件夹
        Files.copy(objStream, Paths.get(localPath), StandardCopyOption.REPLACE_EXISTING);
    }





}
